﻿using eCollabro.Client.ServiceProxy.Interface;
using eCollabro.Utilities;
using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.Practices.Unity;
using eCollabro.Common;

namespace eCollabro.API.App_Start
{
    public class eCollabroAuthorizationProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {

            await Task.Run(() => context.Validated());
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            await Task.Run(() =>
            {
                try
                {
                    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                    ISecurityServiceProxy SecurityClientProcessor = ApplicationContext.Getinstance().UnityContainer.Resolve<ISecurityServiceProxy>();
                    SecurityClientProcessor.AuthenticateUser(context.UserName, context.Password);
                    identity.AddClaim(new Claim("username", context.UserName));
                    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                    context.Validated(identity);
                }
                catch (Exception ex)
                {
                    context.SetError(CoreValidationMessagesConstants.UnAuthorized, ex.Message);
                    return;
                }

            });
        }
    }
}